import {defineStore} from 'pinia'
import type {LoginFrom} from '@/api/system/user/type'
import {reqGetSysUserInfoVO, reqLogin, reqLogout} from '@/api/system/user'
import type {responseType} from '@/api/type'
import type {userState} from './type'
import {removeToken, setToken} from '@/util/token'
import type {SysPermissionTreeVO} from '@/api/system/permission/type'
import router from '@/router'
import {useLayoutStore} from "@/stores/layout";
import {ElMessage} from "element-plus";

const matchView = import.meta.glob('../../views/home/**/**')
export const useUserStore = defineStore('user', {
    state: (): userState => {
        return {
            avatar: '',
            userName: '',
            userId:'',
            sex:'',
            menus: [],
            routers: [],
            permissionsCode: [],
        }
    },
    getters: {},
    actions: {
        userLogin(data: LoginFrom) {
            // 登录后将返回的token存起来，并跳转
            return reqLogin(data).then((res: responseType<string>) => {
                // 保存token
                setToken(res.data);
            })
        },
        getPermission() {
            return reqGetSysUserInfoVO().then(res => {
                // 设置菜单信息
                this.menus = res.data.menus
                // 设置权限码
                this.permissionsCode = res.data.permissionsCode
                this.userName = res.data.sysUser.nickName
                this.sex=res.data.sysUser.sex
                this.avatar = res.data.sysUser.avatar
                this.userId = res.data.sysUser.userId
                // 处理路由格式(只有菜单才有路由，目录无路由(所有菜单路由属于同一级)
                /**
                 * this.routers = res.data.routers.map(item => {
                    return {
                        path: item.url,
                        name: item.permissionKey,
                        meta: {
                            title: item.permissionName,//用于面包屑展示
                            pId: item.permissionId
                        },
                        component: matchView[`../../views/home/${item.component}`],
                        children: []
                    }
                })
                */
                // 处理路由格式（目录也有路由，目录下的菜单属于其子路由），如果想要转换上面的，需要修改数据库的一些信息
                this.routers = res.data.menus.map(item => {
                    return this.routerFormat(item)
                })
            }).catch(err => {
                console.log("动态路由处理处，前往userStore中查看", err);
            })
        },
        routerFormat<RouteRecordRaw>(item: SysPermissionTreeVO) {
            //    构造路由格式
            return {
                path: item.url,
                name: item.permissionKey,
                component: item.permissionType == 0 ? null : matchView[`../../views/home/${item.component}`],//如果类型是目录，则component可以为空
                meta: {
                    title: item.permissionName,//在tab中展示的标题，在面包屑中展示
                    isClosable: item.isClosable//在tab中标志是否可关闭，0为可关闭，1为不可关闭
                },
                children: item.children.length == 0 ? [] : item.children.map(ele => {
                    return this.routerFormat(ele)//递归，该方式要保证后端传的数据是一个树结构！
                })
            } as RouteRecordRaw;
        },
        logout() {
            reqLogout().then(res => {
                removeToken()//移除token
                this.$reset()
                const layoutStore = useLayoutStore()
                layoutStore.$reset()
                window.sessionStorage.clear()
                router.push('/login')
            })
        }
    }
})

